package com.atguigu.ting.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.ting.realtime.app.BaseApp;
import com.atguigu.ting.realtime.bean.PayVipBean;
import com.atguigu.ting.realtime.common.Constant;
import com.atguigu.ting.realtime.util.AtguiguUtil;
import com.atguigu.ting.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/4/14 12:49
 */
public class DwsPayVipWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsPayVipWindow().init(
            40013,
            2,
            "DwsPayVipWindow",
            Constant.TOPIC_DWD_TRADE_PAY_SUCCESS
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
       
        stream
            .map(JSON::parseObject)
            // 过滤出 vip 充值 或续费记录
            .filter(obj -> "1701".equals(obj.getString("item_type")))
            .keyBy(obj -> obj.getString("user_id") + "_" + obj.getString("item_name"))
            .process(new KeyedProcessFunction<String, JSONObject, PayVipBean>() {
            
                private ValueState<String> lastVipDateState;
            
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastVipDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastVipDate", String.class));
                }
            
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<PayVipBean> out) throws Exception {
                    Long ts = obj.getLong("payment_time");
                    String today = AtguiguUtil.tsToDate(ts);
                    String lastVipDate = lastVipDateState.value();
                    long vipDurationUserCt = 0; // 升级或续费改 vip时长的人数
                    if (!today.equals(lastVipDate)) {
                        lastVipDateState.update(today);
                        vipDurationUserCt = 1;
                    }
                    long vipDurationCt = 1; // 级或续费该 vip时长的次数
                
                    out.collect(PayVipBean.builder()
                                    .vipDuration(obj.getString("item_name"))
                                    .vipDurationUserCt(vipDurationUserCt)
                                    .vipDurationCt(vipDurationCt)
                                    .ts(ts)
                                    .build());
                
                }
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<PayVipBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            )
            .keyBy(PayVipBean::getVipDuration)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<PayVipBean>() {
                    @Override
                    public PayVipBean reduce(PayVipBean value1,
                                                  PayVipBean value2) throws Exception {
                        value1.setVipDurationUserCt(value1.getVipDurationUserCt() + value2.getVipDurationUserCt());
                        value1.setVipDurationCt(value1.getVipDurationCt() + value2.getVipDurationCt());
                        return value1;
                    }
                },
                new ProcessWindowFunction<PayVipBean, PayVipBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<PayVipBean> elements,
                                        Collector<PayVipBean> out) throws Exception {
                        PayVipBean bean = elements.iterator().next();
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
                    
                        bean.setTs(System.currentTimeMillis());
                    
                        out.collect(bean);
                    }
                }
            )
            .addSink(FlinkSinkUtil.getClickHouseSink("dws_pay_vip_window", PayVipBean.class));
        
    }
    
}
